package com.ljs.threadpooldemo.controller;

import com.ljs.threadpooldemo.entity.ProgressEntity;
import com.ljs.threadpooldemo.service.FileUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Controller
@Slf4j
public class FileController {
    @Value("${file.linuxPath}")
    String linuxPath;
    @Value("${file.winPath}")
    String winPath;
    @GetMapping("/toFile")
    public String toFile(){
        return "upload";

    }
    @RequestMapping("/upload")
    public  ModelAndView upload(@RequestParam("file") MultipartFile file) throws FileNotFoundException {
        ModelAndView modelAndView=new ModelAndView();
        String os=System.getProperty("os.name");
        log.info("当前系统"+os);
        //获取系统
        String fileRealPath = "";   //文件存放地址
        if (os.toLowerCase().startsWith("win")) {  //windows系统
            String path = System.getProperty("user.dir");  //获取项目相对路径
            fileRealPath = path+winPath;
        }else{
            //如果是linux环境下，放在固定路径
            log.info("获取的linux位置{}"+linuxPath);
            if(!StringUtils.isEmpty(linuxPath)){
                fileRealPath =linuxPath;
            }

        }
           Map<String,String> map= FileUtil.upload(file,fileRealPath);
        modelAndView.setViewName("show");
        modelAndView.addObject("map",map);
        return  modelAndView;

    }
    @GetMapping("/show")
    public String show(){
        return "show";
    }

    /**
     * 获取上传进度
     * @param request
     * @return
     */
    @RequestMapping("/getProgress")
    @ResponseBody
    public Map getProgress(HttpServletRequest request){
        Map map=new HashMap();
        HttpSession session=request.getSession();
        ProgressEntity progressEntity= (ProgressEntity) session.getAttribute("progressEntity");
        System.out.println(progressEntity);
        //当前时间
        long nowTime = System.currentTimeMillis();
        //已传输的时间,转化为秒
        long time = (nowTime - progressEntity.getStartTime())/1000+1;
        //传输速度
       Double rate= Double.valueOf(progressEntity.getBytesRead()/time);
        map.put("rate",rate);
         //总时间
        Double sumTime=progressEntity.getContentLength()/rate;
        map.put("sumTime",sumTime);
        //估计剩余时间
        double timeLeft = sumTime - time;
        map.put("timeLeft",timeLeft);
        //完成的百分比
        String percent=  (progressEntity.getBytesRead()*100/progressEntity.getContentLength())+"%";
        map.put("percent",percent);
        //已经完成数单位:M
        double length = ((double) progressEntity.getBytesRead())/1024/1024;
        map.put("length",length);
        //总长度  M
        double totalLength = (double) progressEntity.getContentLength()/1024/1024;
        map.put("totalLength",totalLength);
          return map;
    }
    @GetMapping("/downFile")
    @ResponseBody
    public void  downFile(HttpServletResponse response,@RequestParam("fileName") String fileName) throws UnsupportedEncodingException {
        if(StringUtils.isEmpty(fileName)){
            throw new RuntimeException("文件不能为空");
        }
        //根据操作系统判断
        String os=System.getProperty("os.name");
        log.info("当前系统"+os);
        File file=null;
        String  fileRealPath="";
        //拼接路径要注意，传过来的文件包含了/images
        if(os.toLowerCase().startsWith("win")){
            //如果是windows
            String path = System.getProperty("user.dir");  //获取项目相对路径
            String subStr=winPath.substring(0,winPath.lastIndexOf("/",winPath.lastIndexOf("/")-1));
              fileRealPath =path+subStr ;
        }else if(os.equalsIgnoreCase("Linux")){
            //linux的话
            fileRealPath =linuxPath.substring(0,linuxPath.lastIndexOf("/",linuxPath.lastIndexOf("/")-1));
        }
        String finalName=fileRealPath+fileName;
        log.info("要下载的路径"+finalName);
        file = new File(finalName);
        //先判断文件是否存在
        if(file.exists()){
            FileUtil.downFile(response,fileName,file);

        }else{
            log.error("文件不存在"+finalName);
            throw new RuntimeException("文件不存在");
        }


    }
}
